package me.zhengjie.modules.serviceprovider.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.exception.EntityNotFoundException;
import me.zhengjie.modules.monitor.service.RedisService;
import me.zhengjie.modules.security.utils.VerifyCodeUtils;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderInfo;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderManager;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderPerson;
import me.zhengjie.modules.serviceprovider.repository.TServiceproviderInfoRepository;
import me.zhengjie.modules.serviceprovider.repository.TServiceproviderManagerRepository;
import me.zhengjie.modules.serviceprovider.service.TServiceproviderInfoService;
import me.zhengjie.modules.serviceprovider.service.TServiceproviderManagerService;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderInfoDTO;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderManagerDTO;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderManagerQueryCriteria;
import me.zhengjie.modules.serviceprovider.service.mapper.TServiceproviderManagerMapper;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.service.SmsSerivice;
import me.zhengjie.utils.*;
import me.zhengjie.modules.serviceprovider.repository.TServiceproviderManagerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

/**
* @author xuyukun
* @date 2019-07-20
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TServiceproviderManagerServiceImpl implements TServiceproviderManagerService {
    @Autowired
    private TServiceproviderInfoRepository tServiceproviderInfoRepository;
    @Autowired
    private TServiceproviderManagerRepository tServiceproviderManagerRepository;
    @Autowired
    private TServiceproviderInfoService tServiceproviderInfoService;
    @Autowired
    private TServiceproviderManagerMapper tServiceproviderManagerMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SmsSerivice smsSerivice;

    @Override
    public Object queryAll(TServiceproviderManagerQueryCriteria criteria, Pageable pageable){
        Page<TServiceproviderManager> page = tServiceproviderManagerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tServiceproviderManagerMapper::toDto));
    }

    @Override
    public Object queryAll(TServiceproviderManagerQueryCriteria criteria){
        return tServiceproviderManagerMapper.toDto(tServiceproviderManagerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TServiceproviderManagerDTO findById(Long id) {
        Optional<TServiceproviderManager> tServiceproviderManager = tServiceproviderManagerRepository.findById(id);
        ValidationUtil.isNull(tServiceproviderManager,"TServiceproviderManager","id",id);
        return tServiceproviderManagerMapper.toDto(tServiceproviderManager.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TServiceproviderManagerDTO create(TServiceproviderManager resources) {
        if(tServiceproviderManagerRepository.findByCellphone(resources.getCellphone())!=null){
            throw new BadRequestException("服务商管理人员电话号码重复，请重新输入");
        }
        resources.setUsername(resources.getCellphone()); //账号跟手机合并
        Timestamp date = new Timestamp(System.currentTimeMillis());
        resources.setCreateTime(date);
        TServiceproviderInfo tServiceproviderInfoDTO=tServiceproviderInfoRepository.findById(resources.getServiceproviderId()).get();
        if(tServiceproviderInfoDTO!=null){
            resources.setServiceproviderName(tServiceproviderInfoDTO.getSeproName());
        }
        return tServiceproviderManagerMapper.toDto(tServiceproviderManagerRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchCreate(JSONArray array) {
        TServiceproviderInfo tServiceproviderInfoDTO = null ;
        Timestamp date = new Timestamp(System.currentTimeMillis());
        for(Object _obj: array) {
            JSONObject obj = (JSONObject)_obj;

            String name = obj.getString("name");
            String cellphone = obj.getString("cellphone");
            Long  serviceproviderId = obj.getLong("serviceproviderId");

            if(tServiceproviderInfoDTO == null) {
                tServiceproviderInfoDTO = tServiceproviderInfoRepository.findById(serviceproviderId).get();
            }

            TServiceproviderManager manager = new TServiceproviderManager();
            manager.setName(name);
            manager.setCellphone(cellphone);
            manager.setUsername(cellphone);
            manager.setIsManager(0);
            manager.setPassword(EncryptUtils.encryptPassword("123456"));
            manager.setServiceproviderId(serviceproviderId);
            manager.setServiceproviderName(tServiceproviderInfoDTO.getSeproName());
            manager.setCreateTime(date);
            tServiceproviderManagerRepository.save(manager);

            smsSerivice.sendBatchSms(manager.getCellphone(),"","管理");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object register(JSONObject resouces) {
        String username = resouces.getString("username");
        String cellphone = resouces.getString("cellphone");
        String capta = resouces.getString("captcha");
        String name = resouces.getString("name");

        String key = "sms_" + cellphone;
        String cache = redisService.getCodeVal(key) ;
        if(cache == null || !cache.equals(capta)) {
            throw new BadRequestException("验证码不一致!");
        }
        redisService.delete(key);

        /*
        if(tServiceproviderManagerRepository.findByUsername(username) != null) {
            throw new BadRequestException("该账号已存在");
        }*/
        username = cellphone ;  //也合并
        if(tServiceproviderManagerRepository.findByCellphone(cellphone) != null) {
            throw new BadRequestException("该手机号码已存在");
        }

        Optional<TServiceproviderInfo> optional = tServiceproviderInfoRepository.findBySeproCode(resouces.getString("code"));
        if(optional.isPresent()) {
            throw new BadRequestException("企业信用代码已存在");
        }

        TServiceproviderInfo company = new TServiceproviderInfo();
        company.setSeproName(resouces.getString("seproName"));
        company.setSeproRefeName(resouces.getString("seproRefeName"));
        company.setPostalCode(resouces.getString("postalCode"));
        company.setAddress(resouces.getString("address"));
        company.setContact(resouces.getString("contact"));
        company.setEmail(resouces.getString("email"));
        company.setPhone(resouces.getString("phone"));
        company.setCompanyItemId(resouces.getLong("companyItemId"));
        company.setRegisteredCapital(resouces.getString("registeredCapital"));
        company.setHead(resouces.getString("head"));
        company.setServiceScope(resouces.getString("serviceScope"));
        company.setServiceContent(resouces.getString("serviceContent"));
        company.setRemark(resouces.getString("remark"));
        company.setState(0L);  //待审核
        company.setLisence(resouces.getString("lisence"));
        company.setCode(resouces.getString("code"));
        company.setSeproCode(company.getCode()); //服务商编码

        //写死
        company.setSeproId(17L);
        company.setSeproItemName("一级服务商");

        //默认一个邀请码
        String inviteCode = VerifyCodeUtils.generateInviteCode(8);
        Optional<TServiceproviderInfo> optionalTServiceproviderInfoOptional = tServiceproviderInfoRepository.findByInviteCode(inviteCode);
        while(optionalTServiceproviderInfoOptional.isPresent()) {
            optionalTServiceproviderInfoOptional = tServiceproviderInfoRepository.findByInviteCode(inviteCode);
        }
        company.setInviteCode(inviteCode);

        TServiceproviderInfoDTO dto = tServiceproviderInfoService.create(company);

        TServiceproviderManager manager = new TServiceproviderManager();
        manager.setCellphone(cellphone);
        manager.setCreateTime(new Timestamp(System.currentTimeMillis()));
        manager.setUsername(username);
        manager.setServiceproviderId(dto.getId());
        manager.setServiceproviderName(dto.getSeproName());
        manager.setIsManager(1); //管理员
        manager.setName(name);
        manager.setPassword(EncryptUtils.encryptPassword("123456")); //MD5

        return tServiceproviderManagerRepository.save(manager);
    }

    @Override
    public TServiceproviderManagerDTO findByUsername(String username) {
        TServiceproviderManager person = tServiceproviderManagerRepository.findByUsername(username);
        if(person == null)
            throw new EntityNotFoundException(TServiceproviderManager.class, "username",username);
        else
            return tServiceproviderManagerMapper.toDto(person);
    }

    @Override
    public TServiceproviderManagerDTO findByCellphone(String username) {
        TServiceproviderManager person = tServiceproviderManagerRepository.findByCellphone(username);
        if(person == null)
            throw new EntityNotFoundException(TServiceproviderManager.class, "cellphone",username);
        else
            return tServiceproviderManagerMapper.toDto(person);
    }

    @Override
    public Object resetpassword(JSONObject resouces) {
        String cellphone = resouces.getString("cellphone");
        String capta = resouces.getString("captcha");
        String password = resouces.getString("password");

        String key = "sms_" + cellphone;
        String cache = redisService.getCodeVal(key) ;
        if(cache == null || !cache.equals(capta)) {
            throw new BadRequestException("验证码不一致!");
        }
        redisService.delete(key);


        TServiceproviderManager manager = tServiceproviderManagerRepository.findByCellphone(cellphone);
        if(manager == null) {
            throw new BadRequestException("账号不存在");
        }
        manager.setPassword(password);
        return tServiceproviderManagerRepository.saveAndFlush(manager);
    }

    @Override
    public Object changePassword(String originPassword, String password, Long id) {
        Optional<TServiceproviderManager> managerOptional = tServiceproviderManagerRepository.findById(id);
        if(!managerOptional.isPresent()) {
            throw new BadRequestException("账号不存在");
        }
        TServiceproviderManager manager = managerOptional.get();
        if(!originPassword.equals(manager.getPassword())) {
            throw new BadRequestException("密码错误");
        }
        manager.setPassword(password);
        return tServiceproviderManagerRepository.saveAndFlush(manager);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        Optional<TServiceproviderManager> personOptional = tServiceproviderManagerRepository.findById(id);
        if(!personOptional.isPresent()) {
            throw new BadRequestException("用户不存在");
        }

        tServiceproviderManagerRepository.deleteById(id);
    }

    @Override
    public void update(TServiceproviderManager resources) {
        Optional<TServiceproviderManager> optionalTServiceproviderManager = tServiceproviderManagerRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTServiceproviderManager,"TServiceproviderManager","id",resources.getId());
        TServiceproviderManager tServiceproviderManager = optionalTServiceproviderManager.get();


        resources.setUsername(resources.getCellphone());

        if(!resources.getCellphone().equals(tServiceproviderManager.getCellphone())){
            TServiceproviderManager  manager = tServiceproviderManagerRepository.findByCellphone(resources.getCellphone());
            if(manager != null && !manager.getId().equals(resources.getId())){
                throw new BadRequestException("服务商人员账号重复，请重新输入");
            }
        }
        // 此处需自己修改
        resources.setId(tServiceproviderManager.getId());
        if(StringUtils.isEmpty(resources.getPassword())){
            resources.setPassword(tServiceproviderManager.getPassword());
        }

        Timestamp date = new Timestamp(System.currentTimeMillis());
        resources.setCreateTime(date);
        TServiceproviderInfo tServiceproviderInfoDTO=tServiceproviderInfoRepository.findById(resources.getServiceproviderId()).get();
        if(tServiceproviderInfoDTO!=null){
            resources.setServiceproviderName(tServiceproviderInfoDTO.getSeproName());
        }
        tServiceproviderManagerRepository.save(resources);
    }
}
